package binary_search;

public class Demo20250330 {
    /**
     * 搜索插入位置
     */
    public int searchInsert(int[] nums, int target) {
        int left = 0;
        int right = nums.length - 1;
        while (left < right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] < target) {
                left = mid + 1;
            } else {
                right = mid;
            }
        }
        // 判断一下第三种情况，索引在数组外边
        if (nums[left] < target) {
            return left + 1;
        }
        return left;
    }

    /**
     * 在排序数组中查找元素的第一个和最后一个位置复习
     */
    public int[] searchRange(int[] nums, int target) {
        // 初始化数组
        int[] ret = new int[2];
        ret[0] = -1;
        ret[1] = -1;
        // 处理边界情况
        if (nums.length == 0) {
            return ret;
        }
        // 1.查找左端点
        int left = 0;
        int right = nums.length - 1;
        while (left < right) {
            int mid = left + (right - left) / 2; // 防止越界
            if (nums[mid] < target) {
                left = mid + 1;
            } else {
                right = mid;
            }
        }
        // 判断是否有结果
        if (nums[left] != target) {
            return ret;
        } else {
            ret[0] = left;
        }
        // 2. 查找右端点
        // 不需要再初始化左端点 int left = 0，因为左端点已经找到了
        right = nums.length - 1;
        while (left < right) {
            int mid = left + (right - left + 1) / 2; // 防止越界
            if (nums[mid] > target) {
                right = mid - 1;
            } else {
                left = mid;
            }
        }
        ret[1] = right;
        return ret;
    }
}
